from pieceConstants import *

class Message:
    def __init__(self, type, args):
        self.type = type
        self.args = args
    
    def getInfo(self):
        string = '%s: {' % self.type
        for i in args.keys:
            string = string + '%s = %s' % (i, self.args[i])
        string = string + '}'
        return string
    
class ClientThread(threading.Thread):

        def __init__(self, server, clientPool):
            self.clientPool = clientPool
            self.server = server
            threading.Thread.__init__(self)

        def run(self):
            while True:
                client = self.clientPool.get()
                if client != None:
                    ret = None
                    curTime = time.strftime("%H:%M:%S", time.localtime())
                    print curTime + ': Received connection:', client[1][0]
                    size = int(client[0].recv( BUFF ))
                    client[0].sendall('passed')
                    try:
                        msg = pickle.loads(client[0].recv(size))
                    except EOFError:
                        pass
                    print '  recieved message: ' + msg.getInfo
                    client[0].close()
                    if msg.type == HOSTING:
                        self.server.turn = msg.args[PLAYER]
                        self.server.board = msg.args[BOARD]
                        self.server.rules = msg.args[RULES]
                    elif msg.type == TURN_OVER:
                        currentPlayer = msg.args[PLAYER]
                        self.server.board = msg.args[BOARD]
                        if currentPlayer == P1:
                            self.server.turn = P2
                        elif currentPlayer == P2:
                            if rules[FOUR_PLAYERS]:
                                self.server.turn = P3
                            else:
                                self.server.turn = P1
                        elif currentPlayer == P3:
                            self.server.turn = P4
                        elif currentPlayer == P4:
                            self.server.turn = P1
                    ret = Message(RESPONSE, {PLAYER : self.server.turn, BOARD : self.server.board, RULES : self.server.rules})    
                    SEND_TO_CLIENT(client[0], ret)
                    print '  closed connection:', client[1][0]
                    
class Server(threading.Thread):
    
    def __init__(self, port):
        self.port = port
        self.turn = None
        self.board = None
        self.rules = {TEAMS : True, BIG_CATH : True, PLAY_TWICE : False, FOUR_PLAYERS : False}
        threading.Thread.__init__(self)

    def run(self):
        clientPool = Queue.Queue(0)
        for x in xrange (4):
            ClientThread(clientPool, self).start()
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.bind(('', self.port))
        server.listen(5)
        while True:
            clientPool.put(server.accept())             

if __name__ == '__main__':            
    Server(8080).start()